/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2023-01-29 13:36:45
 * @LastEditors: Clark
 * @LastEditTime: 2023-01-30 13:01:38
 * @Description: file content
 */
#include "apue.h"
#include <fcntl.h>

static void lockabyte(const char *name, int fd, off_t offset)
{
    if (writew_lock(fd, offset, SEEK_SET, 1) < 0)
    {
        err_sys("%s: writew_lock error", name);
    }
    printf("%s: got the lock, byte %lld\n", name, (long long)offset);
}

int main(void)
{
    int fd = creat("templock", FILE_MODE);
    if (fd < 0)
    {
        err_sys("create error");
    }

    if (2 != write(fd, "ab", 2))
    {
        err_sys("write error");
    }

    TELL_WAIT();
    pid_t pid = fork();
    if (pid < 0)
    {
        err_sys("fork error");
    }
    else if (0 == pid)
    {
        lockabyte("child", fd, 0);
        TELL_PARENT(getppid());
        WAIT_PARENT();
        lockabyte("child", fd, 1);
    }
    else
    {
        lockabyte("parent", fd, 1);
        TELL_CHILD(pid);
        WAIT_CHILD();
        lockabyte("parent", fd, 0);
    }

    exit(0);
}
